<!--
  * 订货款
  *
-->
<template>
  <div>
    <a-table :dataSource="tableData" :columns="columns" :pagination="false" rowKey="id" size="small" bordered>
      <template #headerCell="{ column }">
        <template v-if="column.dataIndex === 'spec_name'">
          <span>
            预收金额(元)
            <ExclamationCircleFilled style="color: #1677ff" @mouseover="warning" />
          </span>
        </template>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="unsubscribe()" type="link" style="color: orange" v-privilege="'goods:update'" v-if="Number(tableData[0]?.balance) !== 0">退订货款</a-button>
            <a-button @click="unsubscribe1()" type="link" style="color: orange" v-privilege="'goods:update'" v-if="Number(tableData[0]?.balance) !== 0">转预付款</a-button>
            <a-button @click="unsubscribe2()" type="link" v-privilege="'goods:update'" v-if="Number(tableData[0]?.un_payment_amount) !== 0 && tableData[0]?.status == 2 && tableData[0]?.performance_status !== 2">收款</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="open" :title="title" :confirm-loading="loading" @ok="submit" @cancel="cancel" width="550px">
      <a-form :model="form" :rules="rules" :label-col="{ sm: 4 }" ref="formRef">
        <div style="margin-left: 3px; margin-bottom: 15px">可用金额 :{{ tableData[0]?.balance }}元 | 可退金额 :{{ tableData[0]?.refund_balance }}元</div>
        <a-form-item label="退款金额" name="amount" required>
          <a-input v-model:value.trim="form.amount" placeholder="请输入退款金额" disabled />
        </a-form-item>
        <div style="margin-left: 3px; margin-bottom: 15px; color: red">请确保相关的订货单已签收完成，再进行退款，操作不可逆，请谨慎操作</div>
      </a-form>
    </a-modal>
    <a-modal v-model:open="open1" :title="title1" :confirm-loading="loading1" @ok="submit1" @cancel="cancel1" width="550px">
      <a-form :model="form1" :rules="rules1" :label-col="{ sm: 6 }" ref="formRef1">
        <div style="margin-left: 20px; margin-bottom: 15px">可用金额 :{{ tableData[0]?.balance }}元 | 可转金额 :{{ tableData[0]?.balance }}元</div>
        <a-form-item label="转预付款金额" name="amount" required>
          <a-input v-model:value.trim="form1.amount" placeholder="请输入转预付款金额" disabled />
        </a-form-item>
        <div style="margin-left: 20px; margin-bottom: 15px; color: red">请确保相关的订货单已签收完成，再进行转款，操作不可逆，请谨慎操作</div>
      </a-form>
    </a-modal>
    <a-modal v-model:open="open2" :title="title2" :confirm-loading="loading2" @ok="submit2" @cancel="cancel2" width="550px">
      <a-form :model="form2" :rules="rules2" :label-col="{ sm: 6 }" ref="formRef2">
        <div style="margin-left: 45px; margin-bottom: 15px">未收金额 :{{ tableData[0]?.un_payment_amount }}元</div>
        <a-form-item label="现金金额" name="amount" required>
          <a-input-number v-model:value.trim="form2.amount" placeholder="请输入现金金额" :min="1" />
        </a-form-item>
        <a-form-item label="折让金额" name="discount_amount">
          <a-input-number v-model:value.trim="form2.discount_amount" :max="form2.amount" placeholder="请输入折让金额" :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { reactive, watch, ref } from 'vue'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { contractApi } from '@/api/business/marketing/contract-api'
import { useLoadingStore } from '@/store/modules/loading-store'
const loadingStore = useLoadingStore()
const props = defineProps({
  enterpriseId: {
    type: Array,
    default: null
  }
})
// 退订货款
const open = ref(false)
const title = ref('退订货款')
const loading = ref(false)
const formRef = ref()
const defaultForm = {
  amount: ''
}
const form = ref(defaultForm)
const rules = reactive({
  amount: [{ required: true, message: '请输入退款金额', trigger: 'blur' }]
})
function unsubscribe() {
  open.value = true
}
function submit() {
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        const data = {
          ...form.value,
          book_order_id: tableData.value[0].id
        }
        await contractApi.doRefund(data)
        message.success('操作成功')
        cancel()
        detail(tableData.value[0])
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

function cancel() {
  open.value = false
  formRef.value.resetFields()
}
// 转预付款
const open1 = ref(false)
const title1 = ref('转预付款')
const loading1 = ref(false)
const formRef1 = ref()
const defaultForm1 = {
  amount: ''
}
const form1 = ref(defaultForm1)
const rules1 = reactive({
  amount: [{ required: true, message: '请输入转预付款金额', trigger: 'blur' }]
})
function unsubscribe1() {
  open1.value = true
}
function submit1() {
  formRef1.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        const data = {
          ...form1.value,
          book_order_id: tableData.value[0].id
        }
        await contractApi.doTransfer(data)
        message.success('操作成功')
        cancel1()
        detail(tableData.value[0])
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}
function cancel1() {
  open1.value = false
  formRef1.value.resetFields()
}

// 收款
const open2 = ref(false)
const title2 = ref('收款')
const loading2 = ref(false)
const formRef2 = ref()
const defaultForm2 = {
  amount: '',
  discount_amount: ''
}
const form2 = ref(defaultForm2)
const rules2 = reactive({
  amount: [{ required: true, message: '请输入现金金额', trigger: 'blur' }]
})
function unsubscribe2() {
  open2.value = true
}
function submit2() {
  formRef2.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        const data = {
          amount: Number(form2.value.amount),
          discount_amount: Number(form2.value.discount_amount),
          book_order_id: tableData.value[0].id
        }
        await contractApi.doPayment(data)
        message.success('操作成功')
        cancel2()
        detail(tableData.value[0])
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}
function cancel2() {
  open2.value = false
  formRef2.value.resetFields()
}

const isWarningShown = ref(false)

const warning = () => {
  if (!isWarningShown.value) {
    message.warning('仅用于支付订货商品货款')
    isWarningShown.value = true
  }
}

const columns = reactive([
  {
    title: '订货金额(元)',
    dataIndex: 'detail_sum'
  },
  {
    title: '预收金额(元)',
    dataIndex: 'advance_amount'
  },
  {
    title: '待收金额(元)',
    dataIndex: 'un_payment_amount'
  },
  {
    title: '已核销',
    dataIndex: 'verified_amount'
  },
  {
    title: '可用金额(元)',
    dataIndex: 'balance'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right'
  }
])

const tableData = ref([])

const detail = async (rowData) => {
  try {
    const res = await contractApi.detailBook({ id: rowData.id })
    tableData.value = [res.data]
    form.value.amount = res.data.refund_balance
    form1.value.amount = res.data.balance
    form2.value.amount = res.data.un_payment_amount
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  }
}

watch(
  () => props.enterpriseId,
  (e) => {
    if (e) {
      detail(e)
    }
  },
  { immediate: true }
)
</script>
